package com.njitzx.interceptor;


import com.njitzx.exception.LoginErrorException;
import com.njitzx.properties.JwtProperties;
import com.njitzx.util.BaseContext;
import com.njitzx.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@RestController
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进行登录拦截器");
        //需要携带token  如果没有token 那么就是说拜拜你嘞
        if (!(handler instanceof HandlerMethod)){
            return  true;
        }
        String token = request.getHeader("Authorization");
        System.out.println("token"+token);

      try {
          Claims claims = JwtUtil.parseJWT("njitzx", token);

          Integer id = claims.get("id", Integer.class);
          BaseContext.setCurrentId(id);
          System.out.println("用户的id" + id);
          return true;
      }catch (Exception ex){
          response.setStatus(401);
          return  false;
      }
    }
}
